package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.service.CiService;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {
    @Resource
    private TencentCloudProperties tencentCloudProperties;

    @Resource
    private CiService ciService;

    /**
     * 上传文件到腾讯云COS
     *
     * @param file 文件
     * @param path 路径
     */
    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        // 生成 cos 客户端。
        COSClient cosClient = this.getCosClient();

        // 文件上传
        // 元数据信息
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentEncoding("UTF-8");
        objectMetadata.setContentType(file.getContentType());

        // 向存储桶中保存文件
        String fileType = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;
        // 01.jpg
        // /driver/auth/0o98754.jpg
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(), uploadPath, file.getInputStream(), objectMetadata);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        putObjectRequest.setStorageClass(StorageClass.Standard);
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown();

        // 审核图片
        Boolean isAuditing = ciService.imageAuditing(uploadPath);
        if (!isAuditing) {
            // 删除违规图片
            cosClient.deleteObject(tencentCloudProperties.getBucketPrivate(), uploadPath);
            throw new GuiguException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }

        // 返回vo对象
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(path);

        // 图片临时访问url，回显使用
        String showUrl = this.getImageUrl(uploadPath);
        cosUploadVo.setShowUrl(showUrl);

        return cosUploadVo;
    }

    /**
     * 获取COS客户端通用方法
     *
     * @return COS客户端对象
     */
    public COSClient getCosClient() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        String secretId = tencentCloudProperties.getSecretId();
        String secretKey = tencentCloudProperties.getSecretKey();
        BasicCOSCredentials basicCOSCredentials = new BasicCOSCredentials(secretId, secretKey);

        // 2 设置 bucket 的地域, COS 地域
        Region region = new Region(tencentCloudProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);

        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);

        // 3 生成 cos 客户端。
        return new COSClient(basicCOSCredentials, clientConfig);
    }

    /**
     * 获取临时签名URL
     *
     * @param path 文件存储路径
     */
    @Override
    public String getImageUrl(String path) {
        if (!StringUtils.hasText(path)) {
            return "";
        }
        // 获取cosClient对象
        COSClient cosClient = this.getCosClient();

        // GeneratePresignedUrlRequest
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(),
                path,
                HttpMethodName.GET);

        // 设置临时URL有效期为15分钟
        Date date = new DateTime().plusMinutes(15).toDate();
        request.setExpiration(date);

        // 调用方法获取
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();

        return url.toString();
    }
}
